import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Input,
  Button,
  Col,
  Row,
  Select,
  Radio,
  InputNumber,
  Divider,
  Spin,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';

import { getParamUrl } from '../../utils/formatDataSource';

@connect(({ role, loading }) => ({
  role,
  loading: loading.models.role,
}))
class RoleAdd extends PureComponent {
  state = {
    subject: '1',
  };

  componentDidMount() {
    const { location: { search }, dispatch } = this.props;
    const params = getParamUrl(search);

    const { userId } = params;

    dispatch({
      type: 'role/jobs',
    });

    if (userId != undefined) {
      dispatch({
        type: 'role/userInfo',
        payload: {
          userId,
        },
      }).then(() => {
        const { userInfo } = this.props.role;
        const { setFieldsValue } = this.props.form;
        setFieldsValue({
          account: userInfo.phone,
          name: userInfo.name,
          age: userInfo.age,
          phone: userInfo.phone,
          qq: userInfo.qq,
          wchat: userInfo.wchat,
          sex: this.sexName(userInfo.sex),
          subject: userInfo.subject + '',
          job: userInfo.roleId,
        });
      });
    }
  }

  sexName = sex => {
    switch (sex) {
      case 1:
        return '男';
      case 2:
        return '女';
      default:
        return '中';
    }
  };

  sexNameCode = sex => {
    switch (sex) {
      case '男':
        return 1;
      case '女':
        return 2;
      case '中':
        return 3;
      default:
        return sex;
    }
  };

  hasErrors = fieldsError => {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);

        const { location: { search }, dispatch } = this.props;

        const params = getParamUrl(search);

        const { userId } = params;
        if (userId != undefined) {
          values.id = userId;
        }

        values.sex = this.sexNameCode(values.sex);

        console.log(values);

        dispatch({
          type: 'role/addUser',
          payload: {
            param: values,
          },
        });
      }
    });
  };

  render() {
    const FormItem = Form.Item;

    const {
      getFieldDecorator,
      getFieldsError,
      getFieldError,
      isFieldTouched,
      setFieldsValue,
    } = this.props.form;

    const Option = Select.Option;

    const RadioGroup = Radio.Group;

    const { jobs } = this.props.role;

    return (
      <PageHeaderLayout>
        <Card
          bordered={false}
          title="账号详情"
          extra={
            <Button
              type="primary"
              size="small"
              onClick={() => this.props.dispatch(routerRedux.push('/personnel/person/role'))}
            >
              返回
            </Button>
          }
        >
          <Spin tip="Loading..." spinning={this.props.loading}>
            <Form layout="horizontal" onSubmit={this.handleSubmit}>
              <Row>
                <Col span={6}>
                  <FormItem label="账号" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('account', {
                      rules: [{ required: true, message: '账号不能为空！' }],
                    })(<Input maxLength={50} />)}
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label="姓名" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('name', {
                      rules: [{ required: true, message: '姓名不能为空!' }],
                    })(<Input maxLength={50} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <FormItem label="职位" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('job', {
                      rules: [{ required: true, message: '职位不能为空!' }],
                    })(
                      <Select placeholder="请选择职位">
                        {jobs.map((e, i) => {
                          return (
                            <Option value={e.id} key={e.id}>
                              {e.name}
                            </Option>
                          );
                        })}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label="性别" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('sex', {
                      rules: [{ required: true, message: '性别不能为空!' }],
                    })(
                      <Select placeholder="请选择性别">
                        <Option value="1">男</Option>
                        <Option value="2">女</Option>
                        <Option value="3">中</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <FormItem label="年龄" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('age', {
                      rules: [
                        { required: true, message: '年龄不能为空!' },
                        { pattern: /^[1-9]{1}$|^[1-9]{2}$/g, message: '年龄不合法!' },
                      ],
                    })(<InputNumber min={1} max={99} style={{ width: '100%' }} />)}
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label="电话" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('phone', {
                      rules: [
                        { required: true, message: '电话不能为空!' },
                        { pattern: /^1\d{10}$/, message: '手机号格式不正确!' },
                      ],
                    })(<Input maxLength={50} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <FormItem label="Q Q" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('qq')(<Input maxLength={50} />)}
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem label="微信" labelCol={{ span: '4' }} wrapperCol={{ span: 14 }}>
                    {getFieldDecorator('wchat')(<Input maxLength={50} />)}
                  </FormItem>
                </Col>
              </Row>

              <Row>
                <Col span={6}>
                  <FormItem label="科目" labelCol={{ span: '4' }} wrapperCol={{ span: 18 }}>
                    {getFieldDecorator('subject')(
                      <RadioGroup>
                        <Row>
                          <Col span={8}>
                            <Radio value="1">数学</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="2">语文</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="3">英语</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="4">物理</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="5">化学</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="6">生物</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="8">历史</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="9">政治</Radio>
                          </Col>
                          <Col span={8}>
                            <Radio value="7">地理</Radio>
                          </Col>
                        </Row>
                      </RadioGroup>
                    )}
                  </FormItem>
                </Col>
              </Row>

              <FormItem>
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={this.hasErrors(getFieldsError())}
                >
                  确认
                </Button>
              </FormItem>
            </Form>
          </Spin>
        </Card>
      </PageHeaderLayout>
    );
  }
}
export default Form.create()(RoleAdd);
